package controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.UserData;
import forms.CaptchaForm;
import forms.UserForm;

import models.UserModel;

public class ResetPasswordServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String code = (String) request.getParameter("key");
		
		TreeMap check = new TreeMap();
		UserData userData = new UserData();
		UserModel user = null;
		if (code != null) {
			user = userData.getUserByCode(code);
		}
		
		if (user != null) {
			user.setPassword("");
		}
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/pages/reset_password.jsp").forward(request,
					response);
		} catch (ServletException e) {

		}
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String code = (String) request.getParameter("key");
		
		UserData userData = new UserData();
		UserModel user = userData.getUserByCode(code);
		
		UserForm userForm = new UserForm();
		TreeMap forms = (TreeMap) userForm.checkValidResetPassword(request, user);
		user = (UserModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0) {
			user.setPassword(StringHelper.md5(user.getPassword()));
			user.setCodeReset("");
			userData.insert(user);
			
			request.setAttribute("success", "Chúc mừng Quý khách đã đổi mật khẩu thành công!");
		}
		
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/pages/reset_password.jsp").forward(request,
					response);
		} catch (ServletException e) {

		}
	}
}
